package com.star.io.netty.socket;

import io.netty.bootstrap.Bootstrap;
import io.netty.buffer.ByteBuf;
import io.netty.channel.*;
import io.netty.channel.nio.NioEventLoopGroup;
import io.netty.channel.socket.SocketChannel;
import io.netty.channel.socket.nio.NioSocketChannel;
import io.netty.handler.codec.LengthFieldBasedFrameDecoder;
import io.netty.handler.codec.LengthFieldPrepender;

public class NettyClient {
    private final String host;
    private final int port;

    public NettyClient(String host, int port) {
        this.host = host;
        this.port = port;
    }

    public void start() throws InterruptedException {
        EventLoopGroup group = new NioEventLoopGroup();
        try {
            Bootstrap b = new Bootstrap();
            b.group(group)
                    .channel(NioSocketChannel.class)
                    .handler(new ChannelInitializer<SocketChannel>() {
                        @Override
                        public void initChannel(SocketChannel ch) throws Exception {
                            ChannelPipeline p = ch.pipeline();
                            // p.addLast(new LengthFieldBasedFrameDecoder(1048576, 8, 2, -12, 0));
                            p.addLast(new LengthFieldBasedFrameDecoder(65536, 0, 4, 0, 4));
                            p.addLast(new LengthFieldPrepender(4));
                            // p.addLast(new CustomFrameDecoder());
                            p.addLast(new ClientHandler());
                        }
                    });

            ChannelFuture f = b.connect(host, port).sync();
            System.out.println( "["+ host + ": "+ port + "]"+"客户端启动成功");
            f.channel().closeFuture().sync();
        } finally {
            group.shutdownGracefully();
        }
    }

    public static void main(String[] args) throws InterruptedException {
        new NettyClient("localhost", 8088).start();
    }
}

class ClientHandler extends SimpleChannelInboundHandler<ByteBuf> {
    @Override
    public void channelActive(ChannelHandlerContext ctx) {
         for (int i = 0; i < 5; ++i) {
             ProtoPacket packet = new ProtoPacket("Fenge" + (i + 1), (byte) i, "Hello from client");
             ByteBuf encode = packet.encode(ctx.alloc());
             ctx.writeAndFlush(encode);
         }
    }

    @Override
    protected void channelRead0(ChannelHandlerContext ctx, ByteBuf msg) throws Exception {
        ProtoPacket packet = ProtoPacket.decode(msg);
        System.out.println("Client received: " + packet);
    }

    @Override
    public void exceptionCaught(ChannelHandlerContext ctx, Throwable cause) {
        cause.printStackTrace();
        ctx.close();
    }
}